package com.jiutong.meipenggang.ui.activitys;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.BaseActivity;
import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.entity.PicUploadBean;
import com.jiutong.meipenggang.http.RetrofitHandle;
import com.jiutong.meipenggang.http.model.requests.ImageUploadRequest;
import com.jiutong.meipenggang.http.subscribers.ProgressSubscriber;
import com.jiutong.meipenggang.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipenggang.utils.ImageUtil;
import com.jiutong.meipenggang.utils.PermissionsResultListener;
import com.jiutong.meipenggang.utils.SpConfig;
import com.jiutong.meipenggang.views.GlideCircleTransform;
import com.jiutong.meipenggang.views.RoundImageView;
import com.jiutong.meipenggang.views.dialog.BaseDialogNormal;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * @author Veken
 */
public class MeActivity extends BaseActivity {

    @Bind(R.id.rl_common_title_back)
    RelativeLayout rlCommonTitleBack;
    @Bind(R.id.tv_common_title)
    TextView tvCommonTitle;
    @Bind(R.id.iv_me_pic)
    RoundImageView ivMePic;

    private BaseDialogNormal photoDialog;
    private String TAG = getClass().getSimpleName();

    private final int REQUEST_ALBUM = 0;
    private final String IMAGE_TYPE = "image/*";
    private final int REQUEST_CAMERA = 1;
    private Bitmap bitmap, bm;
    private String imgPath = "";
    private String picPath;
    private Uri outputFileUri;

    private ImageUploadRequest imageUploadRequest;


    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_me;
    }

    @Override
    protected void initView() {
        super.initView();
        tvCommonTitle.setText("我的");
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        super.initDate(savedInstanceState);
        if (savedInstanceState != null) {
            imgPath = savedInstanceState.getString("picpath");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        picPath = SpConfig.getInstance().getString(Constants.IMAGE_PATH);
        if (!TextUtils.isEmpty(picPath)) {
            Glide.with(this).load(picPath).transform(new CenterCrop(this), new GlideCircleTransform(this))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .crossFade().into(ivMePic);
        } else {
            ivMePic.setImageResource(R.mipmap.icon_personal);
        }
    }

    @OnClick({R.id.rl_common_title_back, R.id.rl_me_pic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_common_title_back:
                finish();
                break;
            case R.id.rl_me_pic:
                showHeadPic();
                break;
            default:
                break;
        }
    }

    /**
     * 判断sdcard是否被挂载
     */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 设置头像dialog
     */
    private void showHeadPic() {
        if (photoDialog == null) {
            photoDialog = new BaseDialogNormal.Builder().
                    layResuorce(R.layout.dialog_headpic).
                    okViewClickEvent(R.id.tv_dialog_take_photo).
                    ok2ViewClickEvent(R.id.tv_dialog_phone).
                    cancelViewClickEvent(R.id.tv_dialog_cancel).
                    gravityStyle(Gravity.BOTTOM).
                    animResource(R.style.dialog_animation).
                    dialogWidth(-1).
                    build();
            photoDialog.setOnDialogClickListener(new BaseDialogNormal.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    //拍照
                    if(photoDialog!=null){
                        photoDialog.dismiss();
                    }
                    performRequestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1, new PermissionsResultListener() {
                        @Override
                        public void onPermissionGranted() {
                            openCamera();
                        }

                        @Override
                        public void onPermissionDenied() {
                            toastShortShow(getResources().getString(R.string.permission_get_accounts_hint));
                        }
                    });
                }

                @Override
                public void onOk2Click() {
                    if(photoDialog!=null){
                        photoDialog.dismiss();
                    }
                    //从手机相册
                    performRequestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1, new PermissionsResultListener() {
                        @Override
                        public void onPermissionGranted() {
                            openAlbum();
                        }

                        @Override
                        public void onPermissionDenied() {
                            toastShortShow(getResources().getString(R.string.permission_get_accounts_hint));
                        }
                    });

                }

            });
        }
        photoDialog.show(getSupportFragmentManager(), TAG);
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        if (hasSdcard()) {
            Date date = new Date();
            // 格式化时间
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String filename = format.format(date) + ".jpg";
            // 启动系统相机
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File fileFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/jiutong/");
            // 如果目录不存在，则创建一个名为"jiutong"的目录
            if (!fileFolder.exists()) {
                fileFolder.mkdir();
            }
            File jpgFile = new File(fileFolder, filename);
            imgPath = jpgFile.getPath();
            int currentapiVersion = Build.VERSION.SDK_INT;
            Uri uri;
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                uri = Uri.fromFile(jpgFile);
                Log.d("uri", uri + "");
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, jpgFile.getAbsolutePath());
                uri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                Log.d("uri", uri + "");
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//            Uri photoUri = Uri.fromFile(jpgFile); // 传递路径
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent getAlbum;
        getAlbum = new Intent(Intent.ACTION_PICK);
//        if (isKitKatO) {
//            getAlbum = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//        } else {
//            getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
//        }
        getAlbum.setType(IMAGE_TYPE);
        startActivityForResult(getAlbum, REQUEST_ALBUM);
    }


    /**
     * 处理图片路径，并显示出来
     */
    private void handleheaderImgToShow() {
        imgPath = compressAfterPath(imgPath);
        if (imgPath != null) {
            imageUpload();
        }
    }

    //接收照片
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果返回数据
        if (resultCode == RESULT_OK) {
            // 拍照数据
            if (requestCode == REQUEST_CAMERA) {
                handleheaderImgToShow();
            } else if (requestCode == REQUEST_ALBUM) {
                // 从相册返回的数据
                if (data != null) {
                    try {
                        outputFileUri = data.getData();
                        String path = getRealPathFromURI(outputFileUri);
                        imgPath = compressAfterPath(path);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (imgPath != null) {
                        imageUpload();
                    }
                }
            }
        }
    }

    /**
     * 压缩过后的图片路径
     * @param path
     * @return
     */
    private String compressAfterPath(String path) {
        bitmap = ImageUtil.getSmallBitmap(path, 120, 240);
        ivMePic.setImageBitmap(bitmap);
        imgPath = ImageUtil.savePhotoToSD(bitmap, mContext);
        Logger.d("图片宽度:"+bitmap.getWidth()+"图片高度:"+bitmap.getHeight()+"图片大小"+bitmap.getByteCount());
        return imgPath;
    }

    /**
     * 图片上传
     */
    private void imageUpload() {
        if (imageUploadRequest == null) {
            imageUploadRequest = new ImageUploadRequest();
        }
        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<PicUploadBean>() {
            @Override
            public void onNext(PicUploadBean subjects) {
                if (subjects.getError() == -1) {
                    toastShortShow(subjects.getMsg());
                    String filename = RetrofitHandle.BASE + subjects.getHeadImg();
                    Logger.d("filename",filename);
                    Glide.with(MeActivity.this).load(filename).centerCrop().into(ivMePic);
                    SpConfig.getInstance().edit().putString(Constants.IMAGE_PATH, filename).commit();
                } else {
                    toastShortShow(subjects.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {
            }
        };
        imageUploadRequest.imgUpload(new ProgressSubscriber(onNextListener, mContext),new File(imgPath));
    }

    /**
     * android4.4以后返回的URI只有图片编号
     * 打开相册得到的uri转为路径
     */
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    /**
     * 在红米note2手机上，当调用相机的时候，Activity会销毁，导致imgPath为空，报空指针异常，所以得保存imgPath
     * 当恢复的时候，再取出来
     *
     * @param outState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("picpath", imgPath);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            imgPath = savedInstanceState.getString("picpath");
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        System.gc();
    }

}
